package com.inforich.app.component;

import com.inforich.common.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: some desc
 * @author: HJM
 * @date: 2022/9/23
 */
@Component
public class TokenUtil {

  // 令牌秘钥
  @Value("${token.secret}")
  private String secret;

  /**
   * 生成token
   *
   * @param userId 用户ID
   * @return String
   */
  public String createToken(String userId, String roleCode) {
    Map<String, Object> claims = new HashMap<>();
    claims.put(Constants.LOGIN_USER_KEY, userId);
    claims.put(Constants.LOGIN_USER_ROLE, roleCode);
    return createToken(claims);
  }

  private String createToken(Map<String, Object> claims) {
    String token = Jwts.builder()
        .setClaims(claims)
        .signWith(SignatureAlgorithm.HS512, secret).compact();
    return token;
  }

  public Claims parseToken(String token) {
    return Jwts.parser()
        .setSigningKey(secret)
        .parseClaimsJws(token)
        .getBody();
  }

  public LoginUserApp getLoginUserApp(String token) {
    Claims claims = parseToken(token);
    String id = String.valueOf(claims.get(Constants.LOGIN_USER_KEY));
    String roleCode = String.valueOf(claims.get(Constants.LOGIN_USER_ROLE));
    LoginUserApp loginUserApp = new LoginUserApp();
    loginUserApp.setId(id);
    loginUserApp.setRoleCode(roleCode);
    return loginUserApp;
  }

  public String getUserId(String token) {
    Claims claims = parseToken(token);
    return String.valueOf(claims.get(Constants.LOGIN_USER_KEY));
  }

  public static void main(String[] args) {

  }
}
